package com.lanou.bookstore.category.web.servlet;

import com.lanou.bookstore.category.domain.Category;
import com.lanou.bookstore.category.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/adminCategory")
public class AdminCategoryServlet extends HttpServlet {
    private CategoryService categoryService = new CategoryService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        String modCname = request.getParameter("cname");
        String method = request.getParameter("method");
        if (cid == null && method == null && modCname == null) {
            String cname = request.getParameter("ccname");
            categoryService.add(cname);
            response.sendRedirect("/adminCategory");
        } else if (cid != null && method == null && modCname == null) {
            categoryService.deleteByCid(cid);
            response.sendRedirect("/adminCategory");
        } else if (cid != null && method != null && modCname != null) {
            categoryService.modifyByCid(cid, modCname);
            response.sendRedirect("/adminCategory");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Category> categoryList = categoryService.findAll();
        request.setAttribute("categoryList", categoryList);
        request.getRequestDispatcher("/adminjsps/admin/category/list.jsp").forward(request, response);


    }
}
